﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Scripni.EditPathVariable.Core;
using GalaSoft.MvvmLight;
using System.Windows.Input;
using GalaSoft.MvvmLight.Command;
using System.Windows.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;

using Scripni.EditPathVariable.UI.Services;
using GalaSoft.MvvmLight.Ioc;

namespace Scripni.EditPathVariable.UI.ViewModels
{
    /// <summary>
    /// Encapsulates the main window functionality.
    /// </summary>
    public class MainViewModel : ViewModelBase
    {
        /// <summary>
        /// Creates a new instance of the <see cref="MainViewModel"/> class.
        /// </summary>
        public MainViewModel()
        {
            this.paths = new ObservableCollection<PathElement>();
            RemoveDuplicates = true;
        }

        private readonly ObservableCollection<PathElement> paths;

        /// <summary>
        /// Gets the collection of paths.
        /// </summary>
        public ObservableCollection<PathElement> Paths { get { return this.paths; } }

        /// <summary>
        /// Gets a command which loads the displayed data.
        /// </summary>
        public ICommand LoadData
        {
            get
            {
                return new RelayCommand(ExecuteLoadData);
            }
        }

        private const string PathVariableName = "PATH";
        private const char PathsSeparator = ';';
        private void ExecuteLoadData()
        {
            Paths.Clear();
            var paths = Environment.GetEnvironmentVariable(PathVariableName)
                .Split(PathsSeparator)
                .Where(p => !string.IsNullOrWhiteSpace(p))
                .OrderBy(p => p)
                .Select(p => p.Trim());
            foreach (string path in paths)
            {
                Paths.Add(new PathElement(path));
            }
        }

        public ICommand AddPathFromDirectory
        {
            get
            {
                return new RelayCommand(ExecuteAddPathFromDirectory);
            }
        }

        public ICommand ExportToCsv
        {
            get
            {
                return new RelayCommand(ExecuteExportToCsv);
            }
        }

        private void ExecuteExportToCsv()
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "Comma separated files (*.csv)|*.csv|All files (*.*)|*.*";

            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                using (StreamWriter file = File.CreateText(saveFile.FileName))
                {
                    foreach (string path in Paths.Select(p => p.Name))
                    {
                        file.WriteLine(path);
                    }
                }
            }
        }

        private void ExecuteAddPathFromDirectory()
        {
            FolderBrowserDialog fBrowser = new FolderBrowserDialog();
            fBrowser.ShowDialog();

            if (Directory.Exists(fBrowser.SelectedPath))
            {
                Paths.Add(new PathElement(fBrowser.SelectedPath));
            }
        }

        /// <summary>
        /// Gets a command which saves all the paths to the path variable.
        /// </summary>
        public ICommand SaveData
        {
            get
            {
                return new RelayCommand(ExecuteSaveData);
            }
        }

        private bool removeDuplicates;

        public bool RemoveDuplicates
        {
            get { return removeDuplicates; }
            set
            {
                if (removeDuplicates != value)
                {
                    removeDuplicates = value;
                    RaisePropertyChanged(() => RemoveDuplicates);
                }
            }
        }

        private void ExecuteSaveData()
        {
            if (Paths.Any(p => p.Error != null))
            {
                IDialogService dialogSvc = SimpleIoc.Default.GetInstance<IDialogService>();

                bool confirm = dialogSvc.ConfirmAction("Attempt to save invalid path",
                    Paths.First(p => p.Error != null).Error + "\n" +
                    "Continue with the save?");
                if (!confirm) return;
            }
            string pathValue = GetPathsAsString();
            Environment.SetEnvironmentVariable(PathVariableName, pathValue, EnvironmentVariableTarget.Machine);
        }

        private string GetPathsAsString()
        {
            var pathsList = (from path in paths
                             select path.Name);

            if (RemoveDuplicates)
            {
                pathsList = pathsList.Distinct();
            }

            StringBuilder sb = new StringBuilder();
            foreach (string path in pathsList)
            {
                sb.Append(path);
                sb.Append(PathsSeparator);
            }
            return sb.ToString();
        }
    }
}
